#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "publics.h"
#include <QStandardPaths>
#include <QMessageBox>
#include <QDate>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QSettings>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    printer = new QPrinter(QPrinter::HighResolution);

    if (QDate::currentDate() > QDate(2014, 11, 30)) {
        QMessageBox::warning(this , "Trial version complete.", "Your trial period is over. Please contact your supplier.");
        qApp->quit();
    }

    odbc_dsn = QSettings(qApp->organizationName(), qApp->applicationDisplayName())
            .value("odbc_dsn", "afex").toString();

    odbc_db = QSqlDatabase::addDatabase("QODBC", "odbc_afex");
    odbc_db.setHostName("127.0.0.1");
    odbc_db.setDatabaseName(odbc_dsn);

    ui->cmdGeneratePDF->setVisible(false);
    ui->cmdPrint->setVisible(false);
    ui->cmdPrintPreview->setVisible(false);

    ui->dtpStartDate->setDate(QDate::currentDate().addMonths(-1));
    ui->dtpStartDate->setEnabled(false);

    if (!odbc_db.open()) {
        QMessageBox::critical(this, "Failed", "<h2>Database Not Connected</h2><br/><span style='color:red'>" + odbc_db.lastError().text());
        //this->setEnabled(false);
        ui->tabWidget->setEnabled(false);
        ui->cboEmployee->setEnabled(false);
        ui->chkAllEmployees->setEnabled(false);
        ui->pushButton->setEnabled(false);
        ui->chkFilterDate->setEnabled(false);
        ui->dtpStartDate->setEnabled(false);
        ui->actionPrint->setEnabled(false);
        ui->actionPrint_Preview->setEnabled(false);
        return;
    }

    //Create unix date time converter.
    QFile unix_time_sql_file(":/sql/UNIX_TO_DATETIME.sql");
    if (unix_time_sql_file.open(QIODevice::ReadOnly)) {
        QString unix_time_sql = unix_time_sql_file.readAll();
        odbc_db.exec(unix_time_sql);
    }

    Publics::loadQueryToComboBox("SELECT * FROM BioStar.dbo.TB_USER ORDER BY sUserName", "sUserName", ui->cboEmployee);

    on_pushButton_clicked();

    tray_icon = new QSystemTrayIcon(this);
    tray_icon->setIcon(this->windowIcon());
    tray_icon->setToolTip(this->windowTitle());
    tray_icon->show();

    connect (tray_icon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), SLOT(tray_show_clicked()));
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    bool allEmployees = false;
    if (ui->chkAllEmployees->isChecked())
        allEmployees = true;

    QString empID = "'";
    QString sql = "";
    if (!allEmployees) {
        empID = Publics::getDbValue("SELECT * FROM BioStar.dbo.TB_USER WHERE sUserName = '" + ui->cboEmployee->currentText()
                                    + "'", "nUserIdn").toString();
    }
    QString sql_extra = "'";
    if (ui->chkFilterDate->isChecked()) {
        sql_extra = "' AND CONVERT(VARCHAR(24), BioStar.dbo.UNIX_TO_DATETIME(nDateTime), 103)  = '"+ ui->dtpStartDate->date().toString("dd/MM/yyyy") +"' ";
    }
    if (!allEmployees) {
        sql = " SELECT BioStar.dbo.TB_USER.sUserName as 'Name',"
              " CONVERT(VARCHAR(24), BioStar.dbo.UNIX_TO_DATETIME(nDateTime), 103) as 'Date',  "
              " CONVERT(VARCHAR(24),DATEADD(MINUTE, nStartTime, '01-01-2000 00:00:00') ,108)  as 'Start Time',"
              " CONVERT(VARCHAR(24),DATEADD(MINUTE, nEndTime, '01-01-2000 00:00:00') ,108)  as 'End Time'"
              " FROM BioStar.dbo.TB_TA_RESULT, BioStar.dbo.TB_USER"
              " WHERE BioStar.dbo.TB_USER.nUserIdn = BioStar.dbo.TB_TA_RESULT.nUserIdn "
              " AND BioStar.dbo.TB_TA_RESULT.nUserIdn = '" + empID +
                sql_extra +
                " ORDER BY BioStar.dbo.TB_USER.sUserName, BioStar.dbo.TB_TA_RESULT.nDateTime";
    } else {
        sql = " SELECT BioStar.dbo.TB_USER.sUserName as 'Name',"
              " CONVERT(VARCHAR(24), BioStar.dbo.UNIX_TO_DATETIME(nDateTime), 103) as 'Date',  "
              " CONVERT(VARCHAR(24),DATEADD(MINUTE, nStartTime, '01-01-2000 00:00:00') ,108)  as 'Start Time',"
              " CONVERT(VARCHAR(24),DATEADD(MINUTE, nEndTime, '01-01-2000 00:00:00') ,108)  as 'End Time'"
              " FROM BioStar.dbo.TB_TA_RESULT, BioStar.dbo.TB_USER"
              " WHERE BioStar.dbo.TB_USER.nUserIdn = BioStar.dbo.TB_TA_RESULT.nUserIdn "
                + sql_extra +
                " ORDER BY BioStar.dbo.TB_USER.sUserName, BioStar.dbo.TB_TA_RESULT.nDateTime";
    }

    qDebug() << sql;
    QSqlQueryModel *model = new QSqlQueryModel(this);
    model->setQuery(sql, odbc_db);

    ui->tblAttendance->setModel(model);

    //Show HTML Preview

    QString html = "<html><body>";

    if (ui->chkAllEmployees->isChecked()) {
        html += "<h2>Attendance for all employees</h2><br/>";
    } else {
        html += QString("<h2>Attendance for %1</h2><br/>").arg(ui->cboEmployee->currentText());
    }

    QString date_text = "";
    if (ui->chkFilterDate->isChecked()) {
        date_text = QString("%1").arg(ui->dtpStartDate->date().toString("dd-MMM-yyyy"));
    }
    html += date_text;

    html += "<table width=65% border=1 cellspacing=1 cellpadding=1>";
    html += "<tr><td><b>Date</b></td><td><b>Name</b></td><td><b>Time In</b></td><td><b>Time Out</b></td><td><b>Hours Worked</b></td></tr>";
    QSqlQuery qu = odbc_db.exec(sql);
    while (qu.next()) {
        QTime timeIn = QTime::fromString(qu.record().value("Start Time").toString(), "hh:mm:ss");
        QTime timeOut = QTime::fromString(qu.record().value("End Time").toString(), "hh:mm:ss");

        double hours = timeIn.secsTo(timeOut);
        hours = hours / 60;
        hours = hours / 60;

        html += QString("<tr><td>%1</td><td>%2</td><td>%3</td><td>%4</td><td>%5</td>")
                .arg(qu.record().value("Date").toString()
                     , qu.record().value("Name").toString()
                     , qu.record().value("Start Time").toString()
                     , qu.record().value("End Time").toString(), QString::number(hours));
    }
    html += "</table>";

    html += "</body></html>";
    ui->textEdit->setHtml(html);
}

void MainWindow::on_cmdPrint_clicked()
{
    printer = new QPrinter(QPrinter::HighResolution);
    printer->setFullPage(true);
    QPrintDialog *dlg = new QPrintDialog(printer, this);

    if (dlg->exec() == QDialog::Accepted) {
        ui->textEdit->print(printer);
    }
}

void MainWindow::on_cmdPrintPreview_clicked()
{
    printer = new QPrinter(QPrinter::HighResolution);
    printer->setFullPage(true);
    QPrintPreviewDialog *dlg = new QPrintPreviewDialog(printer, this);
    connect (dlg, SIGNAL(paintRequested(QPrinter*)), SLOT(printPreview()));
    dlg->exec();
}

void MainWindow::printPreview()
{
    ui->textEdit->print(printer);
}

void MainWindow::on_cmdGeneratePDF_clicked()
{
    printer = new QPrinter(QPrinter::HighResolution);
    printer->setFullPage(true);
    printer->setOutputFormat(QPrinter::PdfFormat);

    QString fileName = QFileDialog::getSaveFileName(this, "Save PDF");
    if (fileName.length() > 0) {
        ui->textEdit->print(printer);
    }
}

void MainWindow::on_actionPrint_triggered()
{
    on_cmdPrint_clicked();
}

void MainWindow::on_actionPrint_Preview_triggered()
{
    on_cmdPrintPreview_clicked();
}

void MainWindow::on_actionE_xit_triggered()
{
    qApp->quit();
}

void MainWindow::on_actionAbout_triggered()
{
    QMessageBox::about(this, "About Attendance Report", "Attendance reports generating tool.\n(c)JWJ 2014\njoejoshw@gmail.com");
}

void MainWindow::on_actionSet_ODBC_Data_Source_triggered()
{
    QString new_dsn = QInputDialog::getText(this, "New DSN", "Enter the new ODBC data source name:", QLineEdit::Normal, odbc_dsn);
    if (new_dsn != odbc_dsn) {
        odbc_dsn = new_dsn;
        QSettings(qApp->organizationName(), qApp->applicationDisplayName())
                .setValue("odbc_dsn", new_dsn);
        QMessageBox::information(this, "New DSN", "To connect to the new data source, please restart the application.");
    }
}

void MainWindow::tray_show_clicked()
{
    if (this->isVisible()) {
        this->hide();
    } else {
        this->show();
    }
}
